import React, { useEffect, useRef, useState } from 'react';

import MainContent from './modules/components/MainContent';
import Sidebar from './modules/components/Sidebar';
import { useAIApi } from './modules/hooks/useAIApi';

import './index.scss';

// 定义视频推荐相关的类型
interface TagDefinition {
	id: string;
	name: string;
	description: string;
}

interface VideoItem {
	id: number;
	title: string;
	tags: string[];
}

// 音频状态接口
interface AudioState {
	fileList: File[];
	recordFile: Blob | null;
	playInfo: {
		localPlay: boolean;
		currentTime: number;
		duration: number;
	};
}

// 视频推荐状态接口
export interface VideoRecommendationState {
	extractedTags: string[];
	matchedVideos: any[];
	isLoading: boolean;
	transcriptionText: string;
	audioState?: AudioState; // 添加音频状态
}

const Home = () => {
	const [infoList, setInfoList] = useState<string>('');
	const [currentTextIndex, setCurrentTextIndex] = useState(0);
	const [displayedText, setDisplayedText] = useState('');
	const textTimerRef = useRef<NodeJS.Timeout | null>(null);
	const [resultObj, setResultObj] = useState<any>({});
	const [activeTab, setActiveTab] = useState<string>('transcribe');
	const [messages, setMessages] = useState<{ role: string; content: string }[]>([]);
	const { callQwen3API } = useAIApi();

	// 视频推荐状态
	const [videoRecommendationState, setVideoRecommendationState] =
		useState<VideoRecommendationState>({
			extractedTags: [],
			matchedVideos: [],
			isLoading: false,
			transcriptionText: '',
			audioState: {
				fileList: [],
				recordFile: null,
				playInfo: {
					localPlay: false,
					currentTime: 0,
					duration: 0
				}
			}
		});

	// 设置默认转写结果
	const defaultTranscript = `你好哎你好，呃，说一下我们验收的一个流程。呃，您看一下车子，然后讲解一下车机，然后前排的话有我们的反光背心用户手册。然后好，谢谢。那我们这边是转账还是刷卡，大概还需要一个小时左右的时间。然后待会还会办理临时牌这些的。然后我先去带您看一下，您的车子已经准备好了。问一下您的车辆驾驶经验如何呢？然后这边的话，您新能源的驾驶经验是三年以内呢，还是三年以上？接下来我将根据以上两个信息为您量身定的。这个是快充口小的充电充加充口哈。然后我们电动关门就可以了，不要去手动关闭。然后右侧的话是这边是我们的加油口，待会我会演示给您看一下。对。我这边是后雨刮和后雨刮的那个喷水加瓜，然后这边是只有瓜，然后这边长按的话它是喷水了。然后我待会帮你设置好，短按的话它是三六零全景影像，这种调整一下，然后帮你保存到你的账号里面。你下一次上车的话，就不需要再去。然后你脚踩一下刹车，车子就可以启动了。这是我们的关爱专员小刘啊，小刘，这是我们的那个m九的车主张先生怎么样提车？好，谢谢张总，非常感谢您的信任与支持，祝您生活愉快，再见，拜拜。`;

	// 组件挂载时设置默认转写结果
	useEffect(() => {
		// 设置默认转写文本
		// setInfoList(defaultTranscript);
		// 触发AI生成会议纪要
		// callQwen3API(defaultTranscript).then(res => {
		// 	if (res?.choices?.[0]) {
		// 		setResultObj(res?.choices?.[0]?.message);
		// 		setMessages([{ role: 'assistant', content: res?.choices?.[0]?.message.content }]);
		// 	}
		// });
	}, []);

	// 文本逐字显示效果
	useEffect(() => {
		if (currentTextIndex < infoList.length) {
			const timer = setTimeout(() => {
				setDisplayedText(displayedText + infoList[currentTextIndex]);
				setCurrentTextIndex(prev => prev + 1);
			}, 32);
			textTimerRef.current = timer;
		}
		return () => {
			if (textTimerRef.current) clearTimeout(textTimerRef.current);
		};
	}, [currentTextIndex, infoList]);

	// 处理类型改变
	const handleTypeChange = (newType: number) => {
		if (newType !== 1) {
			setActiveTab('transcribe');
		}
	};

	// 处理标签页改变
	const handleTabChange = (tab: string) => {
		setActiveTab(tab);
		if (tab === 'welcome') {
			// setType(1);
		}
	};

	// 处理音频识别结果
	const handleAudioResult = (result: string) => {
		const newInfoList = infoList + result;
		setInfoList(newInfoList);

		// 生成会议纪要
		callQwen3API(newInfoList).then(res => {
			if (res?.choices?.[0]) {
				setResultObj(res?.choices?.[0]?.message);
				setMessages([
					...messages,
					{ role: 'assistant', content: res?.choices?.[0]?.message.content }
				]);
			}
		});
	};

	// 处理消息变化
	const handleMessagesChange = (newMessages: { role: string; content: string }[]) => {
		setMessages(newMessages);
	};

	// 处理视频推荐状态变化
	const handleVideoRecommendationStateChange = (newState: Partial<VideoRecommendationState>) => {
		setVideoRecommendationState(prevState => {
			// 特殊处理audioState，确保不会丢失现有的音频状态
			if (newState.audioState) {
				return {
					...prevState,
					...newState,
					audioState: {
						...prevState.audioState,
						...newState.audioState
					}
				};
			}
			return {
				...prevState,
				...newState
			};
		});
	};

	return (
		<div className="w-full bg-white home-page bg-img-cover grid grid-cols-5 gap-x-4">
			<audio id="audioPlayer" className="audio-player" controls style={{ display: 'none' }}></audio>

			<Sidebar />

			<div className="col-span-4 p-8">
				<MainContent
					activeTab={activeTab}
					onTabChange={handleTabChange}
					onTypeChange={handleTypeChange}
					infoList={infoList}
					displayedText={displayedText}
					resultObj={resultObj}
					messages={messages}
					onMessagesChange={handleMessagesChange}
					onAudioResult={handleAudioResult}
					videoRecommendationState={videoRecommendationState}
					onVideoRecommendationStateChange={handleVideoRecommendationStateChange}
				/>
			</div>
		</div>
	);
};

export default Home;
